package pigshare.picture;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSet;

import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pigshare.database.DatabaseConnection;
import pigshare.database.DatabaseManager;

public class ImageServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String cookieValue;
	private java.sql.Blob bl;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		Cookie[] cookies = httpServletRequest.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equalsIgnoreCase("username")) {
					cookieValue = cookies[i].getValue();
				}
			}
		}
		try {
			DatabaseConnection con = new DatabaseConnection();
			ResultSet rs = DatabaseManager.getDatabaseManager().sendQuery(
					"SELECT pic FROM user WHERE username = " + cookieValue
							+ ";");
			if (rs.next()) {
				bl = rs.getBlob("pic");
			}

			response.setContentType("image/jpeg");

			MemoryCacheImageInputStream input = new MemoryCacheImageInputStream(
					bl.getBinaryStream());

			BufferedImage image = ImageIO.read(input);

			OutputStream out = response.getOutputStream();
			ImageIO.write(image, "jpg", out);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}